<template>
  <div class="big">
    <div class="box">
      <h1>商品（Spu）介绍</h1>
      <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
        <!-- 表单 -->
        <a-form @submit="handleSubmit" :form="spuform">
          <a-form-item
            label="商品名称"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
          >
            <a-input
              v-decorator="[
                  'title',
                  { rules: [{ required: true,message:'商品名称不能为空',}]}
                  ]"
            />
          </a-form-item>
          <a-form-item
            label="最小价格"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
          >
            <a-input
              v-decorator="[
                      'minPrice',
                      {rules: [{ required: true, message: '最小价格不能为空' ,}]}
                      ]"
              name="minPrice"
              addonAfter="元"
              placeholder="0.00"
            />
          </a-form-item>
          <a-form-item
            label="商品最大价格"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
          >
            <a-input
              v-decorator="[
                      'maxPrice',
                      {rules: [{ required: true, message: '商品最大价格不能为空' }]}
                      ]"
              name="maxPrice"
              addonAfter="元"
              :initialValue="1"
              placeholder="0.00"
            />
          </a-form-item>
          <a-form-item
            label="剩余库存"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20}}"
            :required="false"
          >
            <a-input disabled="disabled" v-decorator="['stock',]" />
          </a-form-item>
          <a-form-item
            label="运费模板"
            has-feedback
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 8}, sm: {span: 8}}"
          >
            <!-- 下拉列表 -->
            <a-select v-decorator="['select',]" @change="freightFormworkChange">
              <a-select-option  v-for="(item,index) in Freight" :value="item.freightTemplateDO.id" :key=index>{{item.freightTemplateDO.templateName}}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="是否在售" :labelCol="{lg: {span: 4}, sm: {span: 4}}" :required="true">
            <a-radio-group
              @change="onChange"
              v-decorator="[
                    'status',]"
            >
              <a-radio :value="1">在售</a-radio>
              <a-radio :value="0">下架</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="商品图片" :labelCol="{lg: {span: 4}, sm: {span: 4}}">
            <div class="clearfix">

              <a-upload
                action="http://admin.huajianmo.com/api/upload/admin"
                list-type="picture-card"
                :file-list="fileList"
                @preview="handlePreview"
                @change="handleChange"
              >
                <div v-if="fileList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>

            </div>
          </a-form-item>
          <a-form-item
            label="商品单位"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
          >
            <a-input
              v-decorator="[
                      'unit',
                      {rules: [{ required: true, message: '物件单位不能为空' }]}
                      ]"
              name="unit"
              placeholder="件/个/盒"
            />
          </a-form-item>
          <a-form-item
            label="所属类目"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 10} }"
          >
            <div class="block">
              <!-- 级联选择树 -->
              <el-cascader
                ref="cascderselect"
                :options="classoptions"
                :props="{ expandTrigger: 'hover' }"
                @change="cascderchange"
                v-model="selectedOptions"
              ></el-cascader>
            </div>
          </a-form-item>
          <a-form-item
            label="商品简介"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
          >
            <a-input
              v-decorator="[
                      'description',
                      ]"
              name="description"
            />
          </a-form-item>
          <!-- 富文本编辑器 -->
          <a-form-item
            label="商品详情介绍"
            :labelCol="{lg: {span: 4}, sm: {span: 4}}"
            :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
            :required="true"
          >
          <!-- 富文本框 -->
            <QuillEditor
              v-decorator="[
                      'detail',
                      ]"
              ref="goodsDetail"
            ></QuillEditor>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <!-- 商品类型sku -->
    <div class="box1">
      <h1>商品类型（Sku）</h1>
      <a-button class="btn-b" type="primary" @click="skuShowModal">添加</a-button>
      <a-table :columns="skuType" :dataSource="skuListData" rowKey="barCode">
        <span slot="originalPrice" slot-scope="text">{{ text }}</span>
        <span slot="price" slot-scope="text">{{ text }}</span>
        <span slot="vipPrice" slot-scope="text">{{ text }}</span>
        <a
          slot="action"
          slot-scope="text,record"
          href="javascript:;"
          v-if="skuListData.name!=''"
          @click="delSku(record)"
        >删除</a>
      </a-table>
    </div>
    <!--  sku添加模态框   -->
    <a-modal :visible="skuShow" title="添加商品类型（Sku）" @cancel="closeModel">
      <!-- 按钮 -->
      <template slot="footer">
        <a-button key="back" @click="handleCancelcancel" style="margin-left: 8px">取消</a-button>
        <a-button key="submit" @click="skuhandleOk" type="primary">确定</a-button>
      </template>
      <a-form @submit="handleSubmitbox1" :form="skuform">
        <a-form-item
          label="类型条码"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
        >
          <a-input
            @blur="handleSubmitbox1"
            name="barCode"
            v-model="barCode"
          />
        </a-form-item>
        <a-form-item
          label="类型名称"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
        >
          <a-input
            v-decorator="[
                  'title',
                  {rules: [{ required: true,message:'类型名称不能为空'}]}
                  ]"
            @blur="handleSubmitbox1"
            name="title"
          />
        </a-form-item>
        <a-form-item label="图片（可空）" :labelCol="{lg: {span: 4}, sm: {span: 4}}">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            action="http://admin.huajianmo.com/api/upload/admin"
            :beforeUpload="beforeUpload"
            @change="handleChangebox1"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="loadingsku ? 'loadingsku' : 'plus'" />
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="原始价格"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
        >
          <a-input
            v-decorator="[
                  'originalPrice',
                  {rules: [{ required: true, message: '商品原价不能为空' }]}
                  ]"
            @blur="handleSubmitbox1"
            name="originalPrice"
            addonAfter="元"
            placeholder="0.00"
          />
        </a-form-item>
        <a-form-item
          label="当前价格"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
        >
          <a-input
            v-decorator="[
                  'price',
                  {rules: [{ required: true, message: '商品现价不能为空' }]}
                  ]"
            @blur="handleSubmitbox1"
            addonAfter="元"
            name="price"
            placeholder="0.00"
          />
        </a-form-item>
        <a-form-item
          label="VIP价格"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20} }"
        >
          <a-input
            v-decorator="[
                  'vipPrice',
                  {rules: [{ required: true, message: '商品vip价格不能为空' }]}
                  ]"
            @blur="handleSubmitbox1"
            name="vipPrice"
            addonAfter="元"
            :initialValue="1"
            placeholder="0.00"
          />
        </a-form-item>
        <a-form-item
          label="库存"
          :labelCol="{lg: {span: 4}, sm: {span: 4}}"
          :wrapperCol="{lg: {span: 20}, sm: {span: 20}}"
          :required="false"
        >
          <a-input
            placeholder
            v-decorator="[
                  'stock',
                  {rules: [{ required: true, message: '库存不能为空' }]},
                  ]"
            @blur="handleSubmitbox1"
            name="stock"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 商品参数 -->
    <div class="box2">
      <h1>商品参数</h1>
      <a-button class="btn-b" type="primary" @click="showModalbox2">添加</a-button>
      <a-table :columns="commodityParameters" :dataSource="attributeData" rowKey="value">
        <a slot="action" slot-scope="text,record" href="javascript:;" @click="delGoodsAttribute(record)">删除</a>
      </a-table>
    </div>
    <!-- 参数添加模态框     -->
    <a-modal :visible="show2" title="设置商品参数" @cancel="closeModel">
      <!-- 按钮 -->
      <template slot="footer">
        <a-button key="back" @click="handleCancelbox2" style="margin-left: 8px">取消</a-button>
        <a-button key="submit" @click="handleOkbox2" type="primary">确定</a-button>
      </template>
      <a-form @submit="handleSubmitbox2" :form="parameterform">
        <a-form-item
          label="商品参数名称"
          :labelCol="{lg: {span: 6}, sm: {span: 6}}"
          :wrapperCol="{lg: {span: 16}, sm: {span: 16} }"
        >
          <a-input
            v-decorator="[
                  'attribute',
                  {rules: [{ required: true,message:'属性名称不能为空'}]}
                  ]"
            @blur="handleSubmitbox2"
            name="attribute"
          />
        </a-form-item>
        <a-form-item
          label="商品参数值"
          :labelCol="{lg: {span: 6}, sm: {span: 6}}"
          :wrapperCol="{lg: {span: 16}, sm: {span: 16} }"
        >
          <a-input
            v-decorator="[
                  'value',
                  {rules: [{ required: true,message:'属性值不能为空'}]}
                  ]"
            @blur="handleSubmitbox2"
            name="value"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <div class="btn">
      <a-button @click="changeluyou">取消</a-button>
      <a-button v-if="goodsId" type="primary" @click="updataGoods">更新商品</a-button>
      <a-button v-else type="primary" @click="createGoods">新增商品</a-button>
    </div>
  </div>
</template>
<script>
import QuillEditor from '@/components/Editor/QuillEditor.vue'
import { getDetails, creatGoods, updateGoods, getCategoryTree } from '@/api/mall/goods'
import { getAllFreightTemplate } from '@/api/mall/freightFormwork'
import { skuType,skuListData,commodityParameters,} from '@/const/crud/mall/goods.config.js'

// 商品类型上传图片
function getBase64box(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
// 商品sku上传图片
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  components: {
    QuillEditor
  },
  data() {
    return {
      goodsId: null,
      categoryId: null,
      selectdata: null,
      // sku模态框状态
      skuShow: false,
      show2: false,
      imgbox: [],
      // 商品sku上传图片
      loadingsku: false,
      imageUrl: '',
      barCode: '',
      // 所属类目
      classoptions: null,
      // spu上传图片
      previewVisible: false,
      previewImage: '',
      fileList: [],
      // 创建input输入框
      // spu表单
      spuform: this.$form.createForm(this),
      // sku表单
      skuform: this.$form.createForm(this),
      // 商品参数表单
      parameterform: this.$form.createForm(this),
      // sku表格数据
      skuListData,
      skuType,
      // 商品参数表格数据
      attributeData:[],
      commodityParameters,
      // 数据综合
      goodsDetailData: [],
      parameter: {
        spuId: null //编辑接收Id
      },
      Freight:[],//运费模板
      selectedOptions:[],
    }
  },
  computed: {
  },
created() {
     getCategoryTree(Object.assign(this.parameter)).then(res => {
        this.classoptions = this.getTreeData(res.data)
    })
    if (this.$route.query.id) {
      this.goodsId = this.$route.query.id
      this.parameter.spuId = this.$route.query.id
      //获取商品详情数据
      this.getDetails()
    }else{
      this.skuListData = []
    }
    this.getAllFreightTemplate();
    console.log(this.fileList)
  },
  methods: {
    getAllFreightTemplate(){//获取运费模板
      getAllFreightTemplate().then(res => {
        this.Freight = res.data;
      })
    },
    //数据回显
    getDetails() {
      var that = this;
      getDetails(Object.assign(this.parameter)).then(res => {
        console.log(this.parameter);
        var goodsDetailResult = res.data;
        for(let i=0; i < goodsDetailResult.imgList.length; i++){
          goodsDetailResult.imgList[i]
          var img = {
              uid: -i,
              name: 'image.png',
              status: 'done',
              url: goodsDetailResult.imgList[i],
              response:{url:goodsDetailResult.imgList[i]}
            }
          that.fileList.push(img)
        }
        that.selectedOptions = goodsDetailResult.categoryId;//商品类目
        that.skuListData = goodsDetailResult.skuList;//商品类型
        that.goodsDetailData[1] = goodsDetailResult.skuList;
        that.attributeData = goodsDetailResult.attributeList;//商品参数
        that.goodsDetailData[2] = goodsDetailResult.attributeList;
        that.spuform.setFieldsValue({
          title: goodsDetailResult.title,//商品名称
          minPrice: goodsDetailResult.minPrice,//最小价
          maxPrice: goodsDetailResult.maxPrice,//最大价
          stock: goodsDetailResult.stock,//库存
          select: goodsDetailResult.freightTemplateId,//运费模板id
          status: goodsDetailResult.status,//是否在售状态
          unit: goodsDetailResult.unit,//商品单位
          description: goodsDetailResult.description,//商品简介
          detail: goodsDetailResult.detail
        })
      })
    },

    //   更新商品
    updataGoods() {
      console.log(this.goodsDetailData)
      this.goodsDetailData[3] = this.$refs.goodsDetail.content
      console.log(this.goodsDetailData[3])
      if (this.selectdata == null) {
        this.selectdata = 1
      }
      if (this.categoryId == null) {
        this.categoryId = 1036627
      }
      this.spuform.validateFields((err, values) => {
        if (!err) {
          this.goodsDetailData[0] = values
          this.submit("update")
        } else {
          //console.log("请完善以上信息")
          this.$notification['error']({
            message: '失败',
            description: '请完善表单'
          })
        }
      })
    },
    createGoods(){
      console.log(this.goodsDetailData)
      this.goodsDetailData[3] = this.$refs.goodsDetail.content
      console.log(this.goodsDetailData[3])
      if (this.selectdata == null) {
        this.selectdata = 1
      }
      if (this.categoryId == null) {
        this.categoryId = 1036627
      }
      this.spuform.validateFields((err, values) => {
        console.log(values)
        if (!err) {
          this.goodsDetailData[0] = values
          this.submit("create")
        } else {
          //console.log("请完善以上信息")
          this.$notification['error']({
            message: '失败',
            description: '请完善表单'
          })
        }
      })
    },
    submit(type) {
      console.log(type)
      // console.log(this.bigData);
      var spuDTO = new FormData();
      spuDTO.imgList = [];//图片地址
      spuDTO.attributeList = [];//商品参数列表
      spuDTO.skuList = [];//商品类型列表
      console.log(this.fileList)
      for(let i=0; i < this.fileList.length; i++){
        spuDTO.imgList.push(this.fileList[i].response.url);
      }
      spuDTO.img = this.fileList[0].response.url;
       console.log(this.fileList[0].response.url)
      spuDTO.skuList = this.skuListData;
      spuDTO.attributeList = this.attributeData;
      spuDTO.title = this.goodsDetailData[0].title;
      spuDTO.minPrice = this.goodsDetailData[0].minPrice;
      spuDTO.maxPrice = this.goodsDetailData[0].maxPrice;
      spuDTO.stock = this.goodsDetailData[0].stock;
      spuDTO.select = this.goodsDetailData[0].select;
      spuDTO.status = this.goodsDetailData[0].status;
      spuDTO.unit = this.goodsDetailData[0].unit;
      spuDTO.description = this.goodsDetailData[0].description;
      spuDTO.detail = this.goodsDetailData[0].detail;
      spuDTO.categoryId = this.categoryId;
      if(type == "create"){
          creatGoods(Object.assign(spuDTO)).then(res => {
            this.changeluyou()
          })
      }else{
        spuDTO.id = this.goodsId;
        updateGoods(Object.assign(spuDTO)).then(res => {
            this.changeluyou()
          })
      }
    },
    // 路由跳转
    changeluyou() {
      this.skuListData.splice(0, 1)
      this.attributeData.splice(0, 1)
      this.$router.push({
        path: '/mall/goods/index'
      })
    },
    delSku(row) {
      for (let i = 0; i < this.skuListData.length; i++) {
        if (this.skuListData[i].barCode == row.barCode) {
          this.skuListData.splice(i, 1)
        }
      }
    },
    delGoodsAttribute(row) {
      for (let i = 0; i < this.attributeData.length; i++) {
        if (this.attributeData[i].name == row.name) {
          this.attributeData.splice(i, 1)
        }
      }
    },

    // 单选
    onChange() {},
    // 富文本编辑器
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur(val) {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange(val) {
      //console.log(val)
      return val
    }, // 内容改变事件
    // box1上传图片
    handleChangebox1(info) {
      if (info.file.status === 'uploading') {
        this.loadingsku = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loadingsku = false
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },

    // box上传图片
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64box(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = [];
      this.fileList = fileList;
      console.log(this.fileList)
    },
    // 商品sku展示
    skuShowModal() {
      this.skuShow = true
      this.barCode = this.rondomPass()
    },
    // 运费模板选择
    freightFormworkChange(value) {
      this.selectdata = value
    },
    // 获取所属类目
    cascderchange(val) {
      console.log(val)
      let cascderVal = JSON.stringify(val[2])
      this.categoryId = cascderVal
    },
    // sku模态框确定提交方法
    skuhandleOk(e) {
      let sku = {}//定义一个变量存储sku数据
      this.skuform.validateFields((err, values) => {
        // console.log(values)
        if (!err&&values.vipPrice<=values.price<=values.originalPrice) {
          this.skuShow = false;
          this.confirmLoading = false;
          sku.barCode = this.barCode;
          sku.title = values.title;
          // dat.imgU=this.imageUrl;sku图片路径
          sku.originalPrice = values.originalPrice;
          sku.price = values.price;
          sku.vipPrice = values.vipPrice;
          sku.stock = values.stock;
          this.skuform.resetFields()
          this.skuListData.push(sku)
        }
      })
    },
    // sku取消模态框
    handleCancelcancel(e) {
      this.skuShow = false
    },

    showModalbox2() {
      this.show2 = true
    },
    closeModel(){//关闭商品类型模态框
      this.skuShow = false;
      this.show2 = false;
    },
    handleOkbox2(e) {
      this.parameterform.validateFields((err, values) => {
        let goodsAttribute = {}
        if (!err) {
          // console.log(values);
          goodsAttribute.attribute = values.attribute
          goodsAttribute.value = values.value
          this.show2 = false
          this.confirmLoading = false
          this.parameterform.resetFields()
        }
        this.attributeData.push(goodsAttribute)
      })
    },
    //参数取消模态框
    handleCancelbox2(e) {
      this.show2 = false
    },
    //验证sku表单
    handleSubmit(e) {
      //   e.preventDefault();
      this.spuform.validateFields((err, values) => {
        if (!err) {
          this.goodsDetailData[0] = values
        }
      })
    },
    handleSubmitbox1(e) {
      //   e.preventDefault();
      this.skuform.validateFields((err, values) => {
        if (!err) {
          this.goodsDetailData[1] = values
        }
      })
    },
    handleSubmitbox2(e) {
      //   e.preventDefault();
      this.parameterform.validateFields((err, values) => {
        if (!err) {
          this.goodsDetailData[2] = values
        }
      })
    },
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children == '' || data[i].children == undefined || data[i].children == null) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children)
        }
      }
      return data
    },
    rondomPass(){
      var arr = new Array;
      var arr1 = new Array("0","1","2","3","4","5","6","7","8","9");
      var nonceStr=''
      for(var i=0;i<18;i++){
          var n = Math.floor(Math.random()*10);
          arr[i] =arr1[n] ;
          nonceStr+=arr1[n];
      }
      return nonceStr
    }
  }
  
}
</script>
<style scoped>
.box,
.box1,
.box2 {
  background-color: #fff;
  overflow: hidden;
  margin-bottom: 10px;
  box-shadow: #adadad 0px 0px 5px;
}
.box h1,
.box1 h1,
.box2 h1 {
  font-size: 18px;
  margin: 20px 0 0 15px;
  font-weight: bold;
}
.ant-card-body {
  margin-top: 20px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.btn-b {
  margin: 15px;
}
.ant-table-row td:last-child a {
  display: inline;
  text-decoration: none;
  color: #fff;
  padding: 5px 15px;
  background: #f78989;
  border-radius: 5px;
}
.btn .ant-btn:last-child {
  margin-left: 20px;
}
.ql-editor {
  height: 100px !important;
}
.ant-upload-picture-card-wrapper {
  zoom: 1;
  display: block;
  width: 100%;
}
</style>

